<template>
  <el-dialog
    :model-value="dialogVisible"
    title="编辑学生信息"
    width="500"
    @update:model-value="updateDialogVisible"
  >
    <el-form :model="student" label-width="80px">
      <el-form-item label="名字">
        <el-input v-model="student.name" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="student.phone" />
      </el-form-item>
      <el-form-item label="操行分">
        <el-input-number v-model="student.optionScore" :min="0" :max="100" />
      </el-form-item>
      <el-form-item label="在校状态">
        <el-select v-model="student.absentStatus" placeholder="请选择">
          <el-option label="在校" :value="0" />
          <el-option label="请假" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="student.gender" placeholder="请选择">
          <el-option label="男生" :value="0" />
          <el-option label="女生" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="身份">
        <el-input v-model="student.role" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveStudentInfo">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { StudentInfo } from '@/types/StudentType.ts'

const props = defineProps<{
  dialogVisible: boolean
  student: StudentInfo
}>()

const emits = defineEmits(['update:dialogVisible', 'studentUpdated'])

const updateDialogVisible = (value: boolean) => {
  emits('update:dialogVisible', value)
}

const closeDialog = () => {
  emits('update:dialogVisible', false)
}

const saveStudentInfo = async () => {
  try {
    // 发送更新学生信息的请求
    const studentResponse = await axios.post('/api/student/update', {
      id: props.student.id,
      name: props.student.name,
      phone: props.student.phone,
      optionScore: props.student.optionScore,
      absentStatus: props.student.absentStatus,
      gender: props.student.gender,
      role: props.student.role,
    })

    if (studentResponse.data.code === 0) {
      ElMessage.success('学生信息' + '更新成功')
      closeDialog()
      emits('studentUpdated')
    } else {
      ElMessage.error('更新失败，请重试')
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络连接')
  }
}

onMounted(() => {})
</script>
